require('./index.css');
require('util/imageModal/index.js');
let _util = require('util/util.js');
let ImageModal = require('util/imageModal/index.js');
let _index = require('service/indexService.js');
let CommonModal = require('util/commonModal/index.js');
let navSide = require('../aside/index.js');
let UploadModal = require('util/uploadModal/index.js');


let page = {
    data: {
        imageModal: null,
        commonModal: null,
        uploadModal: null
    },
    init: function () {
        this.onLoad();
        this.bindEvent();
    },
    onLoad: function () {

        _index
            .loadTableInfo({
                //表头字段
                fields: {
                    "fileNumber": "档号",
                    "obituaryName": "逝者姓名",
                    "documents": "相关证件",
                    "opera": "相关操作"
                },
                //格式化数据
                formatterData: function (data, fields) {
                    let formatterArray = [];

                    $.each(data, function (index, value) {
                        let newObj = Object.assign({}, data[index]);
                        newObj.documents = `<a href="#" data-fileId="${value.id}" class="jsOpenImageModal">点击查看</a>`;
                        //     newObj.opera = `
                        //     <a href="#" class="jsEdit opera" data-fileId="${value.boxNo}-${value.fileNo}-${value.positionNo}" title="编辑">
                        //         <i class="fa fa-pencil"></i>
                        //     </a>
                        //     <a href="#" class="jsAddToTrash opera" data-fileId="${value.boxNo}-${value.fileNo}-${value.positionNo}" style="color:red" title="放置回收站">
                        //         <i class="fa fa-trash"></i>
                        //     </a>
                        // `
                        newObj.opera = `
                        <a href="#" class="jsAddToTrash opera" data-fileId="${value.id}" style="color:red" title="放置回收站">
                            <i class="fa fa-trash"></i>
                        </a>
                    `
                        formatterArray.push(newObj);
                    })
                    return formatterArray;
                }
            })
            .then((res) => {
                _util.renderTable({
                    url: 'http://localhost:3000/getCatalogues',
                    // url: _util.getServerUrl + '/catalogue/getCatalogue',
                    fields: res.fields || {},
                    formatterData: res.formatterData,
                    selector: $('#info_table')
                });
            })

        navSide.init({
            name: 'file-manage'
        });
    },
    bindEvent: function () {

        let _this = this;

        //登出
        $('#logoutBtn').on('click', function () {
            window.location.href = './login.html';
        });

        //将单条数据放入回收站
        $(document).on('click', '.jsAddToTrash', function (e) {
            e.stopPropagation();
            if (window.confirm('确定要将该目录放入回收站？')) {
                let fileId = $(this).data('fileid');

                _index
                    .addToTrash({
                        data: fileId
                    })
                    .then(res => {
                        alert('删除成功！')
                    })
            }
        });

        //关闭弹窗
        $(document).on('click', '.close-btn-table , .jsCloseBtn', function () {
            _util.destoryTable($('#credential-table'));
            $('.image-modal-wrapper').hide();
        });

        //关闭弹窗
        $(document).on('click', '.close-btn , .js-close-print-btn', function (e) {
            // $(".credentials-wrapper").hide();
            $(this).parents('.modal').hide();
        });

        //查看提名信息
        $(document).on('click', '.jsOpenImageModal', function (e) {
            let fileid = $(e.currentTarget).data('fileid');

            _index
                .loadCertificatePhotosTable({
                    fileNumber: fileid
                })
                .then(res => {
                    _util.renderTable({
                        fields: {
                            "title": "题名",
                            "date": "日期",
                            "pageNum": "页号",
                            "remarks": "备注"
                        },
                        showRefresh: false,
                        pagination: false,
                        selector: $('#credential-table'),
                        formatterData: _this.formatterData,
                        data: res
                    });

                    $('.image-modal-wrapper').show();
                })
        });


        //新增目录
        $(document).on('click', '.jsAddNew', function (e) {
            this.commonModal ? '' : (this.commonModal = new CommonModal());
            this.commonModal.render({
                container: $('.image-modal-wrapper'),
                add: true
            });
            $('.image-modal-wrapper').css('zIndex', '3');
            $('.image-modal-wrapper').show();

            _index.addCatalogue({
                selector: $('#fileupload'),
                $tableRow: $('.preupload-table > tbody')
            })

        });

        //修改目录
        $(document).on('click', '.jsEdit', function (e) {
            e.preventDefault();

            let fileid = $(this).data('fileid').split('-');
            _this.data.commonModal ? '' : (_this.data.commonModal = new CommonModal());

            _index
                .getFileInfo({
                    data: {
                        boxNo: fileid[0],
                        fileNo: fileid[1],
                        positionNo: fileid[2]
                    }
                })
                .then((res) => {
                    _this.data.commonModal.render({
                        container: $('.image-modal-wrapper'),
                        add: false,
                        data: res[0] || {}
                    });
                    $('.image-modal-wrapper').show();
                })
        });

        //根据点开的table提名查看图片
        $(document).on('click', '.openModalToCheckImg', function (e) {
            let fileid = $(this).data('fileid').split('-');

            _this.data.imageStart = $(this).data('image-start');

            _this.data.imageModal ? '' : (_this.data.imageModal = new ImageModal());

            _index
                .loadImages({
                    data: {
                        boxNo: fileid[0],
                        fileNo: fileid[1],
                        positionNo: fileid[2]
                    }
                })
                .then(res => {
                    _this.data.imageModal.render({
                        container: $('.credentials-wrapper'),
                        data: _this.getClickEntryImage(res[0])
                    });
                    $('.credentials-wrapper').show();
                })
        });

        //excel批量导入
        $(document).on('click', '.jsUploadExcel', function (e) {

            _this.data.uploadModal ? '' : (_this.data.uploadModal = new UploadModal());
            _this.data.uploadModal.render({
                container: $('.upload-wrapper')
            })
            $('.upload-wrapper').show();
        });

        //批量打印excel
        $(document).on('click', '.jsPrint', function (e) {
            $("#start-print-index")
                .val('')
                .parent()
                .siblings()
                .find('input')
                .val('');
            $('.error-msg')
                .hide();
            $('.print-hint-wrapper')
                .show();
        });

        //点击开始打印
        $(document).on('click', '.js-print-btn', function () {
            let startIndex = $("#start-print-index").val(),
                endIndex = $("#end-print-index").val();

            if (!startIndex || !endIndex) {
                $('.error-msg').show();
                return;
            }

        });

        //上传图片modal
        $(document).on('click', '.jsUploadPhotos', function () {
            $('.upload-error')
                .hide();
            $('.photo-upload-wrapper').show();
        });

        $(document).on('click', '.upload-photo-btn', function (e) {
            let fileList = document.getElementById('uploadPhotoZip-btn').files,
                formData = new FormData(),
                $uploadErrDom = $('.upload-error');

            $uploadErrDom.hide();

            if (!fileList.length) {
                let $uploadErrDom = $('.upload-error');
                $uploadErrDom.text('没有选择文件！').show();
                return;
            }

            formData.set('photoZip[]', fileList[0]);

            _index.uploadPhotos({
                formData: formData,
            })
        });

        $(document).on('change', '.upload-photo-btn', function (e) {
            let fileListLenth = this.files,
                $uploadErrDom = $('.upload-error');
            if (!fileListLenth) {
                $uploadErrDom.show();
            } else {
                $uploadErrDom.hide();
            }
        });

        //关键词搜索
        $(document).on('click', '.js-search-keyword', function () {
            let searchByPostion = $('#keyword-select').val(),
                keyword = $('#keyword').val();

            _index.searchByKeyword({
                //表头字段
                fields: {
                    "fileNumber": "档号",
                    "obituaryName": "逝者姓名",
                    "documents": "相关证件",
                    "opera": "相关操作"
                },
                //格式化数据
                formatterData: function (data, fields) {
                    let formatterArray = [];

                    $.each(data, function (index, value) {
                        let newObj = Object.assign({}, data[index]);
                        newObj.documents = `<a href="#" data-fileId="${value.id}" class="jsOpenImageModal">点击查看</a>`;
                        newObj.opera = `
                        <a href="#" class="jsAddToTrash opera" data-fileId="${value.id}" style="color:red" title="放置回收站">
                            <i class="fa fa-trash"></i>
                        </a>
                    `
                        formatterArray.push(newObj);
                    })
                    return formatterArray;
                },
                searchByPostion: searchByPostion === 'position' ? true : false,
                data: keyword
            })
                .then(res => {
                    let tableId = $('#info_table');

                    _util.destoryTable(tableId);

                    _util.renderTable({
                        fields: res.fields || {},
                        formatterData: res.formatterData,
                        selector: tableId
                    });
                })
        });


    },
    formatterData: function (data, fields) {
        let formatterArray = [],
            imagesInfo = data[0].images,
            newData = {
                boxNo: data[0]["boxNo"],
                fileNo: data[0]['fileNo'],
                positionNo: data[0]['positionNo']
            }

        $.each(imagesInfo, function (index, value) {
            let newObj = Object.assign({}, imagesInfo[index]);
            newObj.title =
                `
                <a href="#" class="openModalToCheckImg" data-image-start="${value.pageNum}" data-fileid="${newData.boxNo}-${newData.fileNo}-${newData.positionNo}" title="${newObj.title}">${newObj.title}</a>
            `
            formatterArray.push(newObj);
        })

        return formatterArray;
    },
    //提取点击提名获取到的数据
    getClickEntryImage: function (data) {
        let imageStartIndex = this.data.imageStart,
            imgs = data.documents;

        for (let i = 0, length = imgs.length; i < length; i++) {
            const obj = imgs[i];
            if (obj['pageNum'] === imageStartIndex) {
                return obj;
            }
        }

        return {};
    },
}

$(function () {
    page.init();
})